#include <iostream>
#include <unistd.h>
#include <functional>
#include <string>
#include <memory>
#include <string.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        cout << "Usage: " << argv[0] << " Port" << endl;
        exit(-1);
    }

    uint16_t targetport = stoi(argv[1]);

    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        exit(-1);
    }
    
    struct sockaddr_in server;
    size_t len = sizeof(server);
    memset(&server, 0, len);
    server.sin_family = AF_INET;
    server.sin_port = htons(targetport);
    server.sin_addr.s_addr = INADDR_ANY;
    int n = ::bind(sockfd, (struct sockaddr*)&server, len);
    if (n < 0)
    {
        cout << "bind error" << endl;
        exit(-1);
    }

    while (true)
    {
        char inbuffer[1024] = {0};
        sockaddr_in tmp;
        socklen_t lentmp = sizeof(tmp);
        int m = recvfrom(sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr*)&tmp, &lentmp);
        if (m < 0)
        {
            break;
        }
        else
        {
            inbuffer[m] = 0;
        }
        uint16_t clientport = ntohs(tmp.sin_port);
        string clientip = inet_ntoa(tmp.sin_addr);
        string echo_string_prefix = clientip;
        echo_string_prefix += " ";
        echo_string_prefix += to_string(clientport);
        echo_string_prefix += " ";
        string echo_string = echo_string_prefix + inbuffer;
        cout << echo_string << endl;

        int n = sendto(sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr*)&tmp, lentmp);
    }


    return 0;
}
